package com.connect.report.file.processor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import com.connect.report.dao.ReportEntityDao;
import com.connect.report.entity.ReportEntity;

public class ReportFormatRenderImp implements ReportFormatRender {
	private ReportEntityDao reportEntityDao;
	private String path;
	public void setReportEntityDao(ReportEntityDao reportEntityDao){
		this.reportEntityDao = reportEntityDao;
	}
	public void setPath(String path){
		this.path = path;
	}
	@Override
	public void renderReportIssuer(String date, String acqId,String issId) throws IOException{
		List<ReportEntity> list = reportEntityDao.getReportIssuerEntities(date, issId, acqId);
		reportBuilder("ISSUING",date,list);
	}

	@Override
	public void renderReportAcquirer(String date, String issrId,String acqId) throws IOException{
		List<ReportEntity> list = reportEntityDao.getReportAcquirerEntities(date, acqId, issrId);
		reportBuilder("ACQUIRING",date,list);
	}
	
	private String buildFileName(String fileType,String date){
		date = date.substring(2).replaceAll("-", "");
		return path+fileType+"BAY_BCEL."+date+".txt";
	}
	private String buildHeader(String date){
		String type="0";
		String bank="BAY ";
		date = date.substring(2).replaceAll("-", "");
		String title = "ATM-SWITCHING-DATA";
		String space = " ";
		for(int i=0;i<151;i++){
			space = space + " ";
		}
		return  type+bank+date+title+space;
	}
	private String buildFooter(int records){
		String type = "9";
		String flag = "END";
		String num = String.format("%08d", records);
		String space = " ";
		for(int i=1;i<168;i++){
			space = space + " ";
		}
		return type+flag+num+space;
	}
	
	private void reportBuilder(String type,String date,List<ReportEntity> list) throws IOException{
		// set file name
				String fileName = buildFileName(type,date);
				File file = new File(fileName);
				PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
				// build header
				String header = buildHeader(date);
				pw.println(header);
				// build body
				for(ReportEntity entity : list){
					String record = entity.toString();
					pw.println(record);
				}
				// footer
				String footer = buildFooter(list.size());
				pw.println(footer);
				pw.close();
	}
}
